// import * as WebSocket from "client";
// import WebSocket = require('client')
import WebSocket from 'ws';

import { loadSync } from "protobufjs";

import { GJPacketType } from "common";

const gjvideo = loadSync("GJVideo.proto");
const StreamInfo = gjvideo.lookupType("GJVideo.StreamInfo");
const StreamData = gjvideo.lookupType("GJVideo.StreamData");

//------------------------- config -------------------------
const WEBSOCEKT_HOST = "127.0.0.1";
const WEBSOCEKT_PORT = 9090;
const HEARTBEAT_INTERVAL = 30000;// 30s
const HEARTBEAT_TIMEOUT = HEARTBEAT_INTERVAL + 10000;// +10s

self.importScripts("common.js");
//------------------------- config -------------------------


class Receiver{
    private client:any = null;
    private status:string = "init";
    private req:any = null;
    constructor() {
        this.getClient();
    }
    private getClient(){
        let self = this;
        if(this.client === null){
            const client: any = new WebSocket(`ws://${WEBSOCEKT_HOST}:${WEBSOCEKT_PORT}/`);
            client.on('close', function close(code: number, reason: string) {
                console.log('!!![client.close]!!!');
                console.log(code);
                console.log(reason);
            });
            client.on('error', function error(error: Error) {
                console.log('!!![client.close]!!!');
                console.log(error);
            });
            client.on('message', function message(message: string | Buffer | ArrayBuffer | Buffer[]) {
                // console.log('!!![client.message]!!!');
                console.log(message);
            });

            client.on('open', function open(this: any) {
                console.log('!!![client.open]!!!');
                clearTimeout(this.pingTimeout);
                this.pingTimeout = setTimeout(() => {
                    this.terminate();
                }, HEARTBEAT_TIMEOUT);
                self.status = "ready";
                if(self.req !== null){
                    this.send(self.req);
                }
            });

            client.on('ping', function ping(this: any, data: Buffer) {
                console.log('!!![client.ping]!!!');
                clearTimeout(this.pingTimeout);
                this.pingTimeout = setTimeout(() => {
                    this.terminate();
                }, HEARTBEAT_TIMEOUT);
            });

            client.on('pong', function pong(this: any, data: Buffer) {
                console.log('!!![client.pong]!!!');
                this.isAlive = true;
            });

            client.on('unexpected-response', function unexpected_response(request: any, response: any) {
                console.log('!!![client.unexpected-response]!!!');
                console.log(request);
                console.log(response);
            });

            client.on('upgrade', fonmessageunction upgrade(response: any) {
                console.log('!!![client.upgrade]!!!');
                console.log(response);
            });
        }
        return this.client;
    }
    public receiveStream(url: string, clientId: number, token: string, deviceId: string){
        const message = StreamInfo.create({ clientId: 1, token: "token", deviceId: "hy", onlyVideo: false });
        console.log(`message = ${JSON.stringify(message)}`);
        const buffer = StreamInfo.encode(message).finish();
        console.log(buffer);
        this.req = buffer;
    }
}

let receiver = new Receiver();

self.onmessage = function (evt:any) {
    if (!receiver) {
        return;
    }
    var objData = evt.data;
    switch (objData.t) {
        case kReceiveStreamReq:
            receiver.receiveStream(objData.url, objData.clientId, objData.token, objData.deviceId);
            break;
        case kCloseReceiverReq:
            break;
        default:
        //    console.log("error Worker type");
    }
};